package com.kinon.ceshiaccount.activity;


import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.bean.urgent.U_OrderBean;
import com.kinon.ceshiaccount.bean.urgent.U_OrderDetail;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.util.LoadDialogManager;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.view.CustomDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;


/**
 * Created by luohao on 2017-07-26.
 */

public class UrgentSetActivity extends BaseActivity implements View.OnClickListener{

    private TextView tv_back;
    private TextView btn_urgentOn;
    private TextView btn_pullOrder;
    private TextView btn_pushLunch;
    private TextView btn_pushMakemeal;
    private TextView btn_clearLunch;
    private TextView btn_clearMake;

    //自定义登陆广播Action
    public static final String LOGIN_ACTION = "ON_URGENT";

    private String token;
    private boolean isLunch=false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_urgentset_layout);
        initView();
    }



    private void initView() {
        tv_back= (TextView) findViewById(R.id.tv_back);
        btn_urgentOn= (TextView) findViewById(R.id.btn_urgentOn);
        btn_pullOrder= (TextView) findViewById(R.id.btn_pullOrder);
        btn_pushLunch= (TextView) findViewById(R.id.btn_pushLunch);
        btn_pushMakemeal= (TextView) findViewById(R.id.btn_pushMakemeal);
//        btn_clearLunch= (TextView) findViewById(R.id.btn_clearLunch);
//        btn_clearMake= (TextView) findViewById(R.id.btn_clearMake);
        //创建文件夹
//        createFile();

        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
         token = sp.getString("data", "");

        if(Constant.URGENT_TYPE){
            btn_urgentOn.setText(R.string.off_offline_mode);
            btn_urgentOn.setBackgroundResource(R.drawable.bg_urgent_off);
        }else{
            btn_urgentOn.setText(R.string.on_offline_mode);
            btn_urgentOn.setBackgroundResource(R.drawable.bg_urent_on);
        }
//        getOrderId();
        setOnclick();
    }
    private void setOnclick(){
        tv_back.setOnClickListener(this);
        btn_urgentOn.setOnClickListener(this);
        btn_pullOrder.setOnClickListener(this);
        btn_pushLunch.setOnClickListener(this);
        btn_pushMakemeal.setOnClickListener(this);
//        btn_clearLunch.setOnClickListener(this);
//        btn_clearMake.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_back:
                finish();
                break;
            case R.id.btn_urgentOn:
                urgentOn();
                break;
            case R.id.btn_pullOrder://获得订餐信息
                getOrderMealRecode();
//                getMakemealInfo();
                break;
            case R.id.btn_pushLunch:  //上传刷卡记录
                submitCardRecode();
                break;
            case R.id.btn_pushMakemeal: //提交取餐记录
                submitTakeMealRecode();
                break;
//            case R.id.btn_clearLunch:
//                clearSqlite(U_SettletmentBean.class,"是否清空本地结算和午餐信息");
//                break;
//            case R.id.btn_clearMake:
//                clearSqlite(U_OrderBean.class,"是否清空本地取餐信息");
//                break;
        }
    }

    private void urgentOn(){
        if(Constant.URGENT_TYPE){
            Constant.URGENT_TYPE=false;
            btn_urgentOn.setBackgroundResource(R.drawable.bg_urent_on);
            btn_urgentOn.setText(R.string.on_offline_mode);
            Toast.makeText(getApplicationContext(),"断网模式已关闭",
                    Toast.LENGTH_SHORT).show();

        }else{
            Constant.URGENT_TYPE=true;
            btn_urgentOn.setText(R.string.off_offline_mode);
//            btn_urgentOn.setText("关闭紧急模式");
            btn_urgentOn.setBackgroundResource(R.drawable.bg_urgent_off);
            Toast.makeText(getApplicationContext(),"请注意!断网模式已开启!",
                    Toast.LENGTH_SHORT).show();
        }
        sendLoginBroadcast();
    }

    private void clearSqlite(final Class<?> cal , String msg){
        CustomDialog dialog=new CustomDialog(UrgentSetActivity.this,
                msg, new CustomDialog.DialogClickListener() {
            @Override
            public void onDialogClick(int btn) {
                if(btn==1){
                    try {
                       DataSupport.deleteAll(cal);
                        Mtoast("清除成功");
                    }catch (Exception e){
                        Mtoast("清除失败");
                        e.printStackTrace();
                    }
                }
            }
        });

        dialog.show();
    }


    /**获取订餐记录*/
    private void getOrderMealRecode(){

        Call<BaseBean<ArrayList<U_OrderBean>>> ordercall= HttpManage.getRequestApi()
                .backupGetOrders(SPManage.getInstance().getToken());
        ordercall.enqueue(new MyCallback<BaseBean<ArrayList<U_OrderBean>>>() {
            @Override
            public void onSuccess(Call<BaseBean<ArrayList<U_OrderBean>>> call,
                                  Response<BaseBean<ArrayList<U_OrderBean>>> response) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                BaseBean<ArrayList<U_OrderBean>> bean=response.body();
//                //删除数据库表中的所有数据
//                DataSupport.deleteAll(U_OrderBean.class);
//                for(U_OrderBean i:bean.getData()){
//                    i.save();
//                    for (U_OrderDetail j:i.getDetails()){
//                        j.save();
//                    }
//                }
                //删除数据库表中的所有数据
                DataSupport.deleteAll(U_OrderBean.class);
//                for(U_OrderBean i:bean.getData()){
//                    i.save();
//                    for (U_OrderDetail j:i.getDetails()){
//                        j.save();
//                    }
//                }
                DataSupport.saveAll(bean.getData());
                ArrayList<U_OrderDetail> tetails=new ArrayList<>();
                for(U_OrderBean o:bean.getData()){
                    tetails.addAll(o.getDetails());
                }
                DataSupport.saveAll(tetails);
                Mtoast("获取取餐信息成功");
            }

            @Override
            public void onError(int code, String error) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                Mtoast(error);
            }
        });
    }

    /**提交刷卡记录*/
    private void submitCardRecode(){
        ArrayList<U_SettletmentBean> settleList= (ArrayList<U_SettletmentBean>)
                DataSupport.where("submit=?","0").find(U_SettletmentBean.class);
        if(settleList.size()<=0){
            Toast.makeText(getApplicationContext(),"本地未查询到没有提交的记录",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Gson gson=new Gson();
        String data=gson.toJson(settleList);
        Log.e(TAG, "data== "+data );
        LoadDialogManager.gerInstnce().showProgressDialog
                (UrgentSetActivity.this,"上传中...");

        Call<String> call=HttpManage.getRequestApi(60).backupdealOrder(
                SPManage.getInstance().getToken(),data,settleList.size());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                try {
                    JSONObject object=new JSONObject(response.body());
                    ContentValues values=new ContentValues();
                    values.put("submit",1);
                    DataSupport.updateAll(U_SettletmentBean.class,values,"submit=?","0");
                    Mtoast(object.getString("msg"));
                    //删除数据库表中的所有数据
                    DataSupport.deleteAll(U_SettletmentBean.class);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int code, String error) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                Mtoast(error);
            }
        });
    }

    /**提交取餐记录*/
    private void submitTakeMealRecode(){

        ArrayList<U_OrderBean> orderList= (ArrayList<U_OrderBean>)
                DataSupport.where("submit=? ","0").find(U_OrderBean.class,true);
        if(orderList.size()<=0){
            Toast.makeText(getApplicationContext(),"本地未查询到没有提交的记录",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        Gson gson=new Gson();
        String data=gson.toJson(orderList);
        LoadDialogManager.gerInstnce().showProgressDialog
                (UrgentSetActivity.this,"上传中...");

        Call<String> call=HttpManage.getRequestApi(60).backupdealSorder(
                SPManage.getInstance().getToken(),data,orderList.size());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {

                LoadDialogManager.gerInstnce().dismissProgressDialog();
                try {
                    JSONObject object=new JSONObject(response.body());
                    ContentValues values=new ContentValues();
                    values.put("submit",1);
                    DataSupport.updateAll(U_OrderBean.class,values,"submit=?","0");
                    Mtoast(object.getString("msg")+"");
                    //删除数据库表中的所有数据
                    DataSupport.deleteAll(U_OrderBean.class);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                BaseBean bean=response.body();

            }

            @Override
            public void onError(int code, String error) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                Mtoast(error);
            }
        });
    }


    //向整个应用发送登陆广播事件 ，局部广播，局部广播安全
    private void sendLoginBroadcast() {
        LocalBroadcastManager.getInstance(this)
                .sendBroadcast(new Intent(LOGIN_ACTION));
    }

}
